package psi.services;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Db;

import psi.common.Result;
import psi.common.FIdConst;
import psi.common.PSISessionKit;

public class UserService extends PSIBaseService {

	public Result doLogin(String loginName, String password) {
		Result result = new Result();

		String sql = "";
		sql += " select id from t_user ";
		sql += " where login_name = ? and password = ? and enabled = 1 ";

		String userId = Db.queryStr(sql, loginName, HashKit.md5(password));

		if (userId != null) {
			PSISessionKit.get().setAttribute("loginUserId", userId);
			result.setSuccess(true);
			result.setId(userId);
			
			new BizlogService().insertBizlog("登录系统", "系统");
		} else {
			PSISessionKit.get().setAttribute("loginUserId", null);
			result.setMsg("用户名或者密码错误");
		}

		return result;
	}
	
	public String getLoginUserId() {
		return (String) PSISessionKit.get().getAttribute("loginUserId");
	}

	public boolean hasPermission(String fid) {
		String userId = getLoginUserId();
		if (userId == null) {
			return false;
		}
		
		// 修改我的密码，重新登录，首页，使用帮助，关于，购买商业服务，这六个功能对所有的在线用户均不需要特别的权限
		List<String> idList = new ArrayList<String>();
		idList.add(FIdConst.CHANGE_MY_PASSWORD);
		idList.add(FIdConst.RELOGIN);
		idList.add(FIdConst.HOME);
		idList.add(FIdConst.HELP);
		idList.add(FIdConst.ABOUT);
		idList.add(FIdConst.PSI_SERVICE);
		
		if (fid == null || idList.contains(fid)) {
			return true;
		}

		String sql = "";
		sql += " select count(*) as cnt ";
		sql += " from  t_role_user ru, t_role_permission rp, t_permission p ";
		sql += " where ru.user_id = ? and ru.role_id = rp.role_id ";
		sql += "      and rp.permission_id = p.id and p.fid = ? ";

		return Db.queryLong(sql, userId, fid) > 0;
	}
}